import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/item/article_list_cell.dart';
import 'package:tender_flutter/page/home/model/article_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class ArticleListPage extends StatefulWidget {
  /// 资讯类型
  /// 1 权鸟动态   2 行业前沿
  final int type;

  const ArticleListPage({Key key, this.type}) : super(key: key);

  @override
  _ArticleListPageState createState() => _ArticleListPageState();
}

class _ArticleListPageState extends State<ArticleListPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<ArticleEntity>> _future;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  List<ArticleList> _dataLists = [];

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }
    setState(() {
      _future = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<ArticleEntity>> _getData() async {
    var response = await ApiHome.getArticleList<ArticleEntity>(
      type: widget.type,
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<ArticleEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<ArticleEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              ArticleEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _future = _getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _buildFutureBuilder();
  }

  /// 列表
  Widget _initList() {
    return Padding(
        padding: EdgeInsets.only(top: ScreenAdapter.height(20)),
        child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: true,
            enablePullDown: true,
            onRefresh: _refresh,
            onLoading: _refresh,
            child: ListView.separated(
              itemCount: _dataLists.length,
              itemBuilder: (BuildContext context, int index) {
                ArticleList model = _dataLists[index];
                return ArticleListCell(
                    data: model,
                    onTap: () {
                      LRouter.navigatorCtx(context).push(
                          Routes.articleDetailPage,
                          arguments:
                              ArticleDetailPageArguments(articleId: model.id));
                    });
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  color: ThemeColors.colorType49,
                );
              },
            )));
  }
}
